package tsing.javase.quartz;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Author Tsing/吴清平
 * @Date 2022/11/23 16:36
 * @Version 1.0
 *
 *
 * Quartz使用
 */
public class MainDemo {
    public static void main(String[] args) throws SchedulerException, InterruptedException {
        // 1、创建调度器Scheduler
        SchedulerFactory schedulerFactory = new StdSchedulerFactory();
        Scheduler scheduler = schedulerFactory.getScheduler();
        // 使用jobMap存储job的信息
        JobDataMap jobDataMap = new JobDataMap();
        jobDataMap.put("Tsing'job","ok");
        jobDataMap.put("1","ok");
        jobDataMap.put("2","NG");
        // 2、创建JobDetail实例，并与PrintWordsJob类绑定(Job执行内容)
        JobDetail jobDetail = JobBuilder.newJob(PrintWordJob.class)
                .withIdentity("job1", "group1")
                .usingJobData(jobDataMap) //将jobmap保存到JobDetail中
                .build();
        Date startDate = new Date();
        startDate.setTime(startDate.getTime() + 5000);  //开始时间：5s后
        Date endDate = new Date();
        endDate.setTime(startDate.getTime() + 5000); // 结束时间：开始时间5后
        // 3、构建Trigger实例
        Trigger trigger = TriggerBuilder.newTrigger().withIdentity("trigger1", "triggerGroup1")
                .usingJobData("trigger1", "这是jobDetail1的trigger")
                .startNow()//立即生效
                .startAt(startDate)
                .endAt(endDate)
                .withSchedule(SimpleScheduleBuilder.simpleSchedule()
                        .withIntervalInSeconds(5)//每隔1s执行一次
//                        .repeatForever()).build();//一直执行  //  repeatForever():一直执行    // withRepeatCount(num)重复次数
                        .withRepeatCount(1)).build();//一直执行  //  repeatForever():一直执行    // withRepeatCount(num)重复次数
        //4、执行
        scheduler.scheduleJob(jobDetail, trigger);
        System.out.println("--------scheduler start ! ------------");
        //5.启动
        scheduler.start();
        //睡眠
        TimeUnit.MINUTES.sleep(1);
        TimeUnit.SECONDS.sleep(10);
        scheduler.shutdown();  // 关闭调度器
        System.out.println("--------scheduler shutdown ! ------------");
    }
}
